﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.ExtensibleStorage;

namespace YJKRevitFamilyDataBase
{
	public class EntityUtils
	{
		public static Schema CreateSchema(Guid guid, string name, List<SchemaData> schemaDataList)
		{
			Schema schema = Schema.Lookup(guid);
			if (schema == null)
			{
				SchemaBuilder schemaBuilder = new SchemaBuilder(guid);
				schemaBuilder.SetSchemaName(name);
				foreach (SchemaData schemaData in schemaDataList)
				{
					schemaBuilder.AddSimpleField(schemaData.Name, schemaData.Type);
				}
				return schemaBuilder.Finish();
			}
			return schema;
		}

		public static string GetValueString(Element elem, Guid guid, string fieldName)
		{
			string result;
			try
			{
				Schema schema = Schema.Lookup(guid);
				if (schema != null)
				{
					Entity entity = elem.GetEntity(schema);
					if (entity == null)
					{
						result = "";
					}
					else
					{
						Field field = schema.GetField(fieldName);
						result = entity.Get<string>(field);
					}
				}
				else
				{
					result = "";
				}
			}
			catch
			{
				result = "";
			}
			return result;
		}

		public static void SetValueString(Element elem, Guid guid, string fieldName, string value)
		{
			Transaction transaction = new Transaction(elem.Document, "Tr");
			transaction.Start();
			try
			{
				Schema schema = Schema.Lookup(guid);
				Field field = schema.GetField(fieldName);
				Entity entity = new Entity(schema);
				entity.Set<string>(field, value);
				elem.SetEntity(entity);
				transaction.Commit();
			}
			catch (Exception ex)
			{
				transaction.RollBack();
				MessageBox.Show(ex.Message);
			}
		}
	}
}
